package com.ssi.mrms.utils;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/*
 *
 * Kroekpong Sakulchai
 * File Name : SecurityUtils.java
 * Date : Feb 27, 2013 : Time : 8:37:13 AM
 * Description :
 *
 */

public class SecurityUtils {

	private static final Logger logger = Logger.getLogger(SecurityUtils.class);

	private SecurityUtils() {
	}

	public static String getUserSystemName() {
		return "system";
	}

	public static String getUsername() {
		Authentication auth = SecurityContextHolder.getContext().getAuthentication();
		return auth.getName();
	}

	public static String generatePassword(String password) {
		return generatePassword(password, true);
	}

	public static String generatePassword(String password, boolean isUpperCase) {
		String md5 = null;
		if (StringUtils.isEmpty(password)) {
			throw new NullPointerException();
		}
		try {
			// Create MessageDigest object for MD5
			MessageDigest digest = MessageDigest.getInstance("MD5");
			// Update input string in message digest
			digest.update(password.getBytes(), 0, password.length());
			// Converts message digest value in base 16 (hex)
			md5 = new BigInteger(1, digest.digest()).toString(16);
		} catch (NoSuchAlgorithmException e) {
			logger.error(e.toString(), e);
		}

		return isUpperCase ? md5.toUpperCase() : md5;
	}

}
